<?php

namespace app\department\controller;

use app\department\model\DepartmentUserModel;
use app\department\model\UserModel;
use cmf\controller\AdminBaseController;
use think\console\command\make\Model;

class UserController extends AdminBaseController
{
    /**
     * 员工列表
     * @adminMenu(
     *     'name'   => '员工列表',
     *     'parent' => 'department/department/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '员工列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $where = ['user.user_status' => ['neq', 0]];
        $where_r = [];
        $departments = get_departments();
        if ($departments) {
            $where['dep.id'] = ['in', $departments];
        }

        if (input('keyword')) {
            $keyword = input('keyword');
            $where_r['keyword'] = $keyword;
            $where['user.user_nickname|dep.name|role.name'] = ['like', "%$keyword%"];
        }

        $userModel = new UserModel();
        $lists = $userModel
            ->alias('user')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->join('__ROLE_USER__ role_user', 'user.id = role_user.user_id')
            ->join('__ROLE__ role', 'role.id = role_user.role_id')
            ->where($where)
            ->field([
                'user.*',
                'dep.name as dep_name,dep.id as dep_id',
                'role.name as role_name,role.id as role_id',
            ])
            ->paginate();

        $lists->appends($where_r);

        $page = $lists->render();

        $this->assign('where_r', $where_r);

        $this->assign('lists', $lists);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        if ($this->request->isPost()) {
            $userModel = new UserModel();
            $arrData = $this->request->post();

            if (empty($arrData['dep_id'])) {
                $this->error('部门不能为空！');
            }
            if (empty($arrData['role_id'])) {
                $this->error('职位不能为空！');
            }

            if (!empty($arrData['fr_reset_pass'])) {
                $arrData['user_status'] = 4;
            }
            $result = $userModel->allowField(true)->validate(true)->save($arrData);
            if ($result) {
                $departmentUserModel = new DepartmentUserModel();
                $departmentUserModel->allowField(true)->save([
                    'user_id' => $userModel->id,
                    'dep_id' => $arrData['dep_id']
                ]);
                db('role_user')->insert([
                    'user_id' => $userModel->id,
                    'role_id' => $arrData['role_id']
                ]);
                $this->success(lang("ADD_SUCCESS"), url("index"));
            } else {
                $this->error($userModel->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 编辑
     * @adminMenu(
     *     'name'   => '编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        if ($this->request->isPost()) {
            $userModel = new UserModel();
            $arrData = $this->request->post();

            if (empty($arrData['dep_id'])) {
                $this->error('部门不能为空！');
            }
            if (empty($arrData['role_id'])) {
                $this->error('职位不能为空！');
            }

            if (!$arrData['user_pass']) {
                unset($arrData['user_pass']);
            }

//            $result = $this->validate($this->request->param(), 'user.edit');
//            if ($result !== true) {
//                $this->error($result);
//            }

            $userModel->allowField(true)
                ->save($arrData, ["id" => $arrData["id"]]);

            $departmentUserModel = new DepartmentUserModel();
            $departmentUserModel->save(['dep_id' => $arrData['dep_id']], ['user_id' => $arrData['id']]);

            db('role_user')->where(['user_id' => $arrData['id']])->update(['role_id' => $arrData['role_id']]);
            $this->success(lang("SAVE_SUCCESS"), url("index"));
        }
        $userModel = new UserModel();
        $intId = $this->request->param("id", 0, 'intval');

        $result = $userModel
            ->alias('user')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->join('__ROLE_USER__ role_user', 'user.id = role_user.user_id')
            ->join('__ROLE__ role', 'role.id = role_user.role_id')
            ->field([
                'user.*',
                'dep.name as dep_name,dep.id as dep_id',
                'role.name as role_name,role.id as role_id',
            ])->where(["user.id" => $intId])->find();

        $this->assign('result', $result);
        return $this->fetch();
    }

    /**
     * 离职员工列表
     * @adminMenu(
     *     'name'   => '离职员工列表',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '离职员工列表',
     *     'param'  => ''
     * )
     */
    public function dimission_lists()
    {
        $where = ['user.user_status' => 0];
        $where_r = [];
        $departments = get_departments();
        if ($departments) {
            $where['dep.id'] = ['in', $departments];
        }

        if (input('keyword')) {
            $keyword = input('keyword');
            $where_r['keyword'] = $keyword;
            $where['user.user_nickname'] = ['like', "%$keyword%"];
        }

        $userModel = new UserModel();
        $lists = $userModel
            ->alias('user')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->join('__ROLE_USER__ role_user', 'user.id = role_user.user_id')
            ->join('__ROLE__ role', 'role.id = role_user.role_id')
            ->where($where)
            ->field([
                'user.*',
                'dep.name as dep_name,dep.id as dep_id',
                'role.name as role_name,role.id as role_id',
            ])
            ->paginate();

        $lists->appends($where_r);

        $page = $lists->render();

        $this->assign('where_r', $where_r);

        $this->assign('lists', $lists);
        $this->assign('page', $page);

        return $this->fetch();
    }

    /**
     * 员工离职
     * @adminMenu(
     *     'name'   => '员工离职',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '员工离职',
     *     'param'  => ''
     * )
     */
    public function dimission()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            $this->error('参数错误');
        }
        $userModel = new UserModel();
        $userModel->allowField(true)->save([
            'user_status' => 0
        ], [
            'id' => $id
        ]);
        $this->success('员工离职成功');
    }

    public function select()
    {
        $admin_id = cmf_get_current_admin_id();
        $where = [];
        if ($admin_id != 1) {
            $where['dep.id'] = ['in', getUsersGroup($admin_id)];
        }
        $id = $this->request->param('id', 0, 'intval');
        $userModel = new UserModel();

        $where['user_status'] = ['neq',0];
        $lists = $userModel
            ->alias('user')
            ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
            ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
            ->where($where)
            ->field([
                'user.*',
                'dep.name as dep_name,dep.id as dep_id'
            ])->where($where)->select();

        $this->assign('lists', $lists);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 记录分配
     * @adminMenu_bak(
     *     'name'   => '记录分配',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '记录分配',
     *     'param'  => ''
     * )
     */
    function allot()
    {
        $check_ids = $this->request->param('check_ids', '');
        $table = $this->request->param('table', '');


//        $a = new class extends \think\Model{
//            /* 自动处理时间 */
//            protected $autoWriteTimestamp = 'int';
//        };

//        $buyerUserModel = new BuyerUserModel();
//        if ($this->request->isPost()) {
//            $ids = $this->request->param('ids', 0, 'intval');
//            $buyerUserModel->allowField(true)->save(['uid' => $ids], [
//                'pid' => ['in', $check_ids],
//                'level' => 2
//            ]);
//            $buyerModel = new BuyerModel();
//            $buyerModel->save([
//                'manager' => $ids
//            ], [
//                'id' => ['in', $check_ids],
//            ]);
//            $this->success('设置成功');
//        } else {
//            $userModel = new UserModel();
//
//            $where = [];
//            $uid = cmf_get_current_admin_id();
//            $flag = false;
//            if ($uid != 1) {
//                $roles = db('role_user')
//                    ->where(['user_id' => $uid])
//                    ->column('role_id');
//
//                $role_deps = get_role_department($roles,'data_to_all_user');
//                foreach ($role_deps as $role_dep) {
//                    if ($role_dep['data_to_all_user']) {
//                        $flag = true;
//                    }
//                }
//            }
//
//            if ($uid != 1 && !$flag) {
//                $department = get_user_group($uid);
//                $departments = getGroups($department);
//                $where['dep.id'] = ['in', $departments];
//            }
//            $where['user_status'] = ['neq', 0];
//
//            $lists = $userModel
//                ->alias('user')
//                ->join('__DEPARTMENT_USER__ dep_user', 'user.id = dep_user.user_id')
//                ->join('__DEPARTMENT__ dep', 'dep_user.dep_id = dep.id')
//                ->field([
//                    'user.*',
//                    'dep.name as dep_name,dep.id as dep_id'
//                ])->where($where)->select();
//
//            $users = $buyerUserModel->where([
//                'pid' => ['in', $check_ids],
//                'level' => 2
//            ])->column('uid');
//
//            $this->assign('lists', $lists);
//            $this->assign('users', $users);
//            return $this->fetch();
//        }
    }
}